package com.exsun.ex1077.ui.activity.login

import androidx.lifecycle.MutableLiveData
import com.alibaba.fastjson.JSONObject
import com.blankj.utilcode.util.EncryptUtils
import com.exsun.ex1077.app.Constant
import com.exsun.ex1077.network.apiService
import com.exsun.ex1077.network.entity.Login
import com.zhangping.fastjetpack.base.BaseViewModel
import com.zhangping.fastjetpack.extend.base.ResultState
import com.zhangping.fastjetpack.extend.base.request
import com.zhangping.fastjetpack.extend.databind.BooleanObservableField
import com.zhangping.fastjetpack.extend.databind.StringObservableField

/**
 * 描述：
 * 作者：ZhangPing
 * 创建时间：2023/3/15 16:15
 */
class RegisterViewModel: BaseViewModel() {

    val companyMode = BooleanObservableField()
    val pwdShow = BooleanObservableField()
    val agreement = BooleanObservableField()
    val companyName = StringObservableField()
    val account = StringObservableField()
    val mobile = StringObservableField()
    val smsCode = StringObservableField()
    val password = StringObservableField()

    val registerResult = MutableLiveData<ResultState<Login?>>()

    fun checkAccountAndMobile(): MutableLiveData<Boolean> {
        val liveData = MutableLiveData<Boolean>()
        request({ apiService.checkAccountMobile(mobile.get(), account.get())}, {
            liveData.value = true
        })
        return liveData
    }

    fun sendSms(): MutableLiveData<Boolean>{
        val liveData = MutableLiveData<Boolean>()
        request({ apiService.sendSms(mobile.get())}, {
            liveData.value = true
        }, isShowDialog = true)
        return liveData
    }

    fun register() {
        request({ apiService.register(JSONObject().apply {
            put("username", account.get().trim())
            put("mobile", mobile.get().trim())
            put("codeSMS", smsCode.get().trim())
            put("password", getAesPassword(password.get().trim()))
        })}, registerResult, isShowDialog = true)
    }

    private fun getAesPassword(password: String): String{
        return EncryptUtils.encryptAES2HexString(password.toByteArray(),
            Constant.PASSWORD_AES_SECRET.toByteArray(), "AES/ECB/PKCS5Padding", null)
    }
}